/* =====================================================================================
 * DRIVEBOOK 
 * =====================================================================================*/

		protected void GetInitialKMInfo()
		{
		}
		protected void TimerSecond_Tick(object sender, EventArgs e)
		{
		}
		public void TimerMove_Tick(object sender, EventArgs e)
		{
			WriteDataLog("Car motion detected (Lat:" + cLat.ToString() + "; Lng:" + cLng.ToString()); 
		}
		protected void Ttimer1_Tick(object sender, EventArgs e)
		{
			dis = getDistance(Driving.latitude, Driving.longitude, doubleLat, doubleLng);
			WriteDataLog("Last driven meters: " + Convert.ToString(dis));
            logGoogleRoute(ref Driving);
			Ttimer1.Start();
		}
		protected void TimerPause_Tick(object sender, EventArgs e)
		{
			TimerPause.Stop();
			StopLog();
		}
		public int IntervallTime
		private bool DetectGPS()
		private double deg2rad(double deg)
		private double rad2deg(double rad)
		public double getDistance(double lat1, double lon1, double lat2, double lon2) 
		private void InsertLastTripData(ref GPSLoc gloc)
		{
			//====================================================================================================
			// STARTING THE LOG, first get the old STOP location data and the driven km's
			//====================================================================================================

			int initialkm = 0;
			
			try
			{
                if (drivebook.USEDEBUG) CFTools.writeModuleLog("START", errLog);
				// get to end location record of the last trip and set it to the beginning point of the new trip
				drivebook.dvAll.Dispose();
				drivebook.dvAll = new DataView(drivebook.dsTRIP.Tables["DRIVES"]);
				drivebook.dvAll.Sort = "ID DESC";
			
				#region SECTION NEW CAR FIRST TRIP
				// if recordcount = 0 this car is new in the drives table, so start with the initial km settings
				if (drivebook.dvAll.Count == 0)
				{
					if (drivebook.USEDEBUG) CFTools.writeModuleLog("New cars first trip",errLog);

					if (DetectGPS())
					{
						gloc.latitude = Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LATITUDE));
						gloc.longitude = Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LONGITUDE));
						gloc.city = CF_getGPSInfo(CF_GPSInfo.CITY);
						gloc.zipcode = CF_getGPSInfo(CF_GPSInfo.ZIP);
						gloc.street = CF_getGPSInfo(CF_GPSInfo.STREET);
					}
					else
					{
						gloc.latitude = 0;
						gloc.longitude = 0;
						gloc.city = " ";
						gloc.zipcode = " ";
						gloc.street = " ";
					}
					gloc.name = "Initial Drive";

					XmlNode tmpNode = drivebook.configxml.SelectSingleNode("/APPCONFIG/CARS/CAR[@Registration='" + this.pluginConfig.readPluginField("/APPCONFIG/CAR") + "']");	
					try { initialkm = Convert.ToInt32(tmpNode.Attributes["InitialOdometer"].InnerText);	} 
					catch {initialkm = 0;}
					try { servicekmls = Convert.ToInt32(tmpNode.Attributes["Service"].InnerText);	} 
					catch {servicekmls = 0;}

					gloc.odometer = initialkm;
					gloc.toff = TimeSpan.Zero;
				}
				#endregion SECTION NEW CAR FIRST TRIP

				else
				#region SECTION KNOWN CAR NEXT TRIP
				{
					if (drivebook.USEDEBUG) CFTools.writeModuleLog("Existing cars next trip",errLog);

					//#################################################################################
					// First get the data of the last trip of this car
					//---------------------------------------------------------------------------------
					if (dvAll[0]["LATITUDE"].ToString() == "") gloc.latitude = 0; else gloc.latitude = Convert.ToDouble(dvAll[0]["LATITUDE"].ToString());
					if (dvAll[0]["LONGITUDE"].ToString() == "") gloc.longitude = 0; else gloc.longitude = Convert.ToDouble(dvAll[0]["LONGITUDE"].ToString());
					if (dvAll[0]["ALTITUDE"].ToString() == "") gloc.altitude = 0; else gloc.altitude = Convert.ToDouble(dvAll[0]["ALTITUDE"].ToString());
					
					//#################################################################################
					// if the old latitude and longitude values were 0 then it has been a non GPS trip
					// in this case fetch the current GPS data and insert these.
					//---------------------------------------------------------------------------------
					if ((gloc.latitude == 0) && (gloc.latitude == 0) && DetectGPS())
					{
						gloc.latitude = Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LATITUDE));
						gloc.longitude = Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LONGITUDE));
					}
			
					gloc.city = dvAll[0]["DEST_CITY"].ToString();
					gloc.zipcode = dvAll[0]["DEST_ZIP"].ToString();
					gloc.street = dvAll[0]["DEST_STREET"].ToString();
					gloc.name = dvAll[0]["DEST_NAME"].ToString();

					gloc.odometer = Convert.ToInt32(dvAll[0]["KMSTOP"]); // new start km
					//=======================================================================
					// set the gobal variables for later using of the a cf_plugindata command
					LastDistance = Convert.ToDouble(dvAll[0]["ROUTE"]);
					LastTripTime = Convert.ToDateTime(dvAll[0]["TROUTE"]);
					
					gloc.toff = DateTime.Now.Subtract(Convert.ToDateTime(dvAll[0]["TSTOP"].ToString()));	
				}
				#endregion SECTION KNOWN CAR NEXT TRIP

				gloc.datetime = DateTime.Now;
			}
			catch(Exception errmsg) { CFTools.writeError("InsertLastTripData: " +errmsg.Message, errmsg.StackTrace); }
            if (drivebook.USEDEBUG) CFTools.writeModuleLog("END", errLog);
		}
		private void InsertAutomaticStopData()
		{
			//====================================================================================================
			// STOPPING THE LOG, set the last data to the endpoint of this trip (only GPS mode)
			//====================================================================================================

            if (drivebook.USEDEBUG) CFTools.writeModuleLog("START", errLog);
			try
			{
				string ret = CF_getGPSInfo(CF_GPSInfo.LONGITUDE);
				if (ret == "") StopPoint.longitude = 0; else StopPoint.longitude = Convert.ToDouble(ret);
				ret = CF_getGPSInfo(CF_GPSInfo.LATITUDE);
				if (ret == "") StopPoint.latitude = 0; else StopPoint.latitude = Convert.ToDouble(ret);
				ret = CF_getGPSInfo(CF_GPSInfo.ALTITUDE);
				if (ret == "") StopPoint.altitude = 0; else StopPoint.altitude = Convert.ToDouble(ret);

				StopPoint.datetime = DateTime.Now;
				StopPoint.saveIt = true;

				if (LocationFound(ref StopPoint) == false)	
				{
					if (drivebook.USEDEBUG == true) CFTools.writeModuleLog("No Stop position found in database",errLog);

					StopPoint.city		= CF_getGPSInfo(CF_GPSInfo.CITY);
					StopPoint.zipcode	= CF_getGPSInfo(CF_GPSInfo.ZIP);
					StopPoint.street	= CF_getGPSInfo(CF_GPSInfo.STREET);
					
					if ((StopPoint.city == "") && (StopPoint.street == ""))	// no GPS adress found
						StopPoint.name = "Point " + DateTime.Now.ToString();
					else
						StopPoint.name = StopPoint.city + ", " + StopPoint.street;

					StopPoint.housenumber = CF_getGPSInfo(CF_GPSInfo.HOUSENUMBER);
					
					//StopPoint.reason = "";	// do not define the destination trip reason at this moment

					if (TIsPrivate == true) StopPoint.type = "PRIVATE"; else StopPoint.type = "BUSINESS";
					StopPoint.odometer = StartPoint.odometer + (int)TripDistance;
				}
			}
			catch(Exception errmsg) { CFTools.writeError("InsertAutomaticStopData: " + errmsg.Message, errmsg.StackTrace); }
            if (drivebook.USEDEBUG) CFTools.writeModuleLog("END", errLog);
		}
		private void EditMinimalData(ref GPSLoc gloc)
		private void InsertManualData(ref GPSLoc gloc)
		
		private void DisplayMessage(string msg)
		protected void MessageDisplay()
		public void SoundOutput() 
		private void StartGPSDetection()
		private void GPSReady()
		
		private void AskForDriver()
		private void AskDriver()
		public void ContinueLog()
		{
            if (drivebook.USEDEBUG) CFTools.writeModuleLog("START", errLog);
			try
			{

				/*
				 	//#################################################################################
					// check wether the old stop point is more than
					int dist = (int)getDistance(gloc.latitude, gloc.longitude, 
									Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LATITUDE)),
									Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LONGITUDE)));
					if (dist > Convert.ToInt16(configxml.SelectSingleNode("/APPCONFIG/SEPARATEDISTANCE").InnerText))
					{
						// now it could be a ferry or lorry event
						if (this.CF_systemDisplayDialog(CF_Dialogs.YesNo, this.pluginLang.readPluginField("/APPLANG/DRIVEBOOK/QUERY_TRANSPORTER")) == DialogResult.OK)
						{
							gloc.latitude = Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LATITUDE));
							gloc.longitude = Convert.ToDouble(CF_getGPSInfo(CF_GPSInfo.LONGITUDE));
						}
					}

				 */

				//==================================================================
				// only possible if a trip is running and the button CONTINUE has not 
				// been pressed before

				if (!(tripStatus == status.CONTINUED) && (drivebook.dvAll.Count > 1))
				{
					drivebook.dvAll.Dispose();
					drivebook.dvAll = new DataView(drivebook.dsTRIP.Tables["DRIVES"]);
					drivebook.dvAll.Sort = "ID DESC";

					DataRowView LastTrip = dvAll[0];
					DataRowView PreLastTrip = dvAll[1];
					// get last record out of the drives dataset and fill special fields
					// dvAll[1] is the pre last recorded trip
					//--------------------------------------------------------------
					StartPoint.datetime = Convert.ToDateTime(LastTrip["TSTART"]);

					if (PreLastTrip["LATITUDE"].ToString() == "") StartPoint.latitude = 0; else StartPoint.latitude = (double)(PreLastTrip["LATITUDE"]);
					if (PreLastTrip["LONGITUDE"].ToString() == "") StartPoint.longitude = 0; else StartPoint.longitude = (double)(PreLastTrip["LONGITUDE"]);
					if (PreLastTrip["ALTITUDE"].ToString() == "") StartPoint.altitude = 0; else StartPoint.altitude = (double)(PreLastTrip["ALTITUDE"]);

					StartPoint.odometer = (double)(PreLastTrip["KMSTOP"]);

					// dvAll[0] is the last recorded trip, here we get driven km's to add 
					// to the current trip log and get the last known position to avoid
					// double counting of km's 
					//--------------------------------------------------------------

					//#############################################
					TripDistance += (double)(LastTrip["ROUTE"]);//#
					//#############################################
					
					// now delete to old trip log record dvAll[0]
					LastTrip.Delete();
					// Now set the flags
					tripStatus = status.CONTINUED;
					Ttimer1.Start();
					LastTrip = null;
					PreLastTrip = null;
					drivebook.dvAll.Dispose();
					if (drivebook.USEDEBUG) CFTools.writeModuleLog("Route continued",errLog);
				}
			}
			catch(Exception errmsg) { CFTools.writeError("ContinueLog: " + errmsg.Message, errmsg.StackTrace); }

            if (drivebook.USEDEBUG) CFTools.writeModuleLog("END", errLog);
		}

		#endregion

		#region Service KM / miles
		public  void InitiateKmls()
		{
            if (drivebook.USEDEBUG) CFTools.writeModuleLog("START", errLog);
			XmlNode tmpNode = drivebook.configxml.SelectSingleNode("/APPCONFIG/CARS/CAR[@Registration='" + this.pluginConfig.readPluginField("/APPCONFIG/CAR") + "']");	
			try { 
				servicekmls = Convert.ToInt32(tmpNode.Attributes["Service"].InnerText);	
				servicelast = Convert.ToInt32(tmpNode.Attributes["LastService"].InnerText);	
				} 
			catch 
				{
					servicekmls = 0;
					servicelast = 0;
					if (drivebook.USEDEBUG) CFTools.writeModuleLog("No Service or Lastservice data found",errLog);
				}
			if (drivebook.USEDEBUG) 
				CFTools.writeModuleLog("Service=[" + Convert.ToString(servicekmls) + "], Last Service=[" 
									+ Convert.ToString(servicelast) + "]",errLog);

            if (drivebook.USEDEBUG) CFTools.writeModuleLog("END", errLog);
		}

		private bool GetServicekmls(int kmls)
		private bool IsOverMaxSpeed()
		private void LoadDataBase()
		private void FillTripList(int cntTrips)		
		private bool LocationFound (ref GPSLoc gloc)
		private void SaveTripToDatabase()		
		private string GetPositionType(double lat, double lng)
        public void SaveTrip()
		public void StartLog()
		{
            if (drivebook.USEDEBUG) CFTools.writeModuleLog("START", errLog);
			
			// if automatic motion detection is temporary switched off, reactivate it
			if (configxml.SelectSingleNode("/APPCONFIG/ENABLEMOTIONDETECT").InnerText.Trim().ToUpper() == "FALSE")
				{
					configxml.SelectSingleNode("/APPCONFIG/ENABLEMOTIONDETECT").InnerText = "TRUE";
					this.CF_updateText("MESSAGE", "");
				}
			
			DisplayMessage(this.pluginLang.readPluginField("/APPLANG/DRIVEBOOK/STARTLOG"));

			try
			{
				InsertLastTripData(ref StartPoint);

				// take the detected start point as the first driving point
				Driving = StartPoint;
				TripDistance = 0;
				TIsPrivate = false;
							
				GetInitialKMInfo();

				StartPoint.withGPS = DetectGPS();
				
				if (StartPoint.withGPS)
				{
					kmlStatus = (int)status.START;
					Ttimer1.Enabled = true;			// start the current log process and the position detection
				}

				if (this.pluginConfig.readPluginField("/APPCONFIG/SOUND/USESOUND").ToUpper() == "TRUE")
				{
					sMsg = this.pluginConfig.readPluginField("/APPCONFIG/SOUND/FILESTART");
					
					if (File.Exists(sMsg)) 
					{
						this.CF_playAudioFile(sMsg);
						this.Focus();
					}
				}
	
				this.CF_setButtonOff("PRIVATE");
				
				TimerSecond.Enabled = true;
				tripStatus = status.RUNNING;
			}
			catch(Exception errmsg) { CFTools.writeError("StartLog: " + errmsg.Message, errmsg.StackTrace); }

            if (drivebook.USEDEBUG) CFTools.writeModuleLog("END", errLog);
		}

		public void StopLog()
		{
			
				{
					SaveTrip();
					SaveTripToDatabase();
					LoadDataBase();
					RefillTripList();
				}
			
				this.CF_updateText("DRIVETIME",this.pluginLang.readPluginField("/APPLANG/DRIVEBOOK/LBLTRIPLOGEND"));
			
				this.CF_updateText("PERCENTAGE","");
				this.CF_setButtonOff("PRIVATE");
				this.CF_setButtonOff("CONTINUE");

				#region MOTION CONTROL restart
				//=================================================================================
				//=== Restart the Motion Control System ===========================================
				//=================================================================================
				try
				{
					if (this.pluginConfig.readPluginField("/APPCONFIG/ACTIVATED").ToUpper() == "TRUE")
					{
						bStartTimerMove = true;	 // work around for thread save timer
						InsertLastTripData(ref StartPoint); // get the current position as a reference
						TimerMove.Enabled = true;
					}
				}
				catch(Exception errmsg) { CFTools.writeError("GPSReady: " + errmsg.Message, errmsg.StackTrace); }
				#endregion MOTION CONTROL restart

				//=================================================================================
				//=== Play the trip stop sound  ===================================================
				//=================================================================================

		}

		public static string LimitLength (string input, int maxLength)
		public void RefillTripList()
		{
			FillTripList(Convert.ToInt16(this.pluginConfig.readPluginField("/APPCONFIG/TRIPSINLIST")));
		}

		private bool IsVehicleMoved()
		public drivebook()	
		public override void CF_pluginInit()
		{
                this.loadSettings();
		}

		public override void CF_pluginShow()
		{
                if ((!DetectGPS()) && !(tripStatus == status.RUNNING)) ...				
                RefillTripList();
		}

		public override void CF_pluginClose()
		{
            Ttimer1.Stop();
			TimerMove.Stop();
			TimerSecond.Stop();
			
			StopLog();	
		}
		
		public override void CF_pluginUpdateLanguageSkin(string language, string skin) 
		{
			loadSettings();
		}
		
		public override DialogResult CF_pluginShowSetup()
		public override string CF_pluginData(string command, string param)
		public void loadSettings()
		{				
			this.CF_localskinsetup();
		}
		public override void CF_localskinsetup()
		private void drivebook_CF_Event_applicationLoaded(object sender, EventArgs e)
		{
				Ttimer1.Enabled = false;
				TimerMove.Enabled = true;
				TimerPause.Enabled = false;
				if (this.pluginConfig.readPluginField("/APPCONFIG/ASKFORDRIVER").ToUpper() == "TRUE") AskForDriver();
					StartGPSDetection(); 											// start thread to detect whether GPS information is available
          
		}
        private void drivebook_CF_Event_powerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
        {
            if (e.Mode.ToString() == "Suspend")
            {
                // Die Ausfhrung des Betriebssystems wird unterbrochen
                if (drivebook.USEDEBUG == true) { CFTools.writeModuleLog("CF_Event_powerModeChanged - Mode: Suspend", drivebook.errLog); }
            }
            else if (e.Mode.ToString() == "Resume")
            {
                // Das Betriebssystem steht unmittelbar davor, aus dem Ruhezustand fortgesetzt zu werden. 
                if (drivebook.USEDEBUG == true) { CFTools.writeModuleLog("CF_Event_powerModeChanged - Mode: Resume", drivebook.errLog); }
                loadSettings();
            }
        }
		private string GetNextKMLFileName()
		private void InitializeComponent()
		private void LogGoogleRoute(ref GPSLoc Driving)